﻿using LDT.CoreLibrary;
using LdtDataEngin.ModuleDetail.AnalysisModule.CaseCauseBaseInfoExtr;
using LdtDataEngin.ModuleDetail.AnalysisModule.SituationPlot;
using LdtDataEngin.ModuleDetail.BaseModule;
using LdtDataEngin.ModuleDetail.CommonModule.PersonMerger;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.ConfigXmlLoad;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.CircumsatanModel;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.CaseCauseElementExtr
{
    /// <summary>
    /// 案由要素提取模块
    /// </summary>
    public class CaseCauseElementExtractAssemble : AssermBase
    {
        DataContext _dataContext; 
        public CaseCauseElementExtractAssemble(DataContext dataContextIn, string moudleName)
        {
            _dataContext = dataContext = dataContextIn;
            base.MoudleName = moudleName;
        }

        /// <summary>
        /// 开始提取
        /// </summary>
        /// <param name="Name">模块名称</param>
        public void Extrat()
        {
            #region 获取案由要素提取配置
            var configModel = dataContext.DataLayerSys.GetConfigModel(MoudleName);
            if (_dataContext.DataLayerAns.CaseCausesList.Count > 0)
            {
                if (configModel.ConfigContent != null )
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(configModel.ConfigContent);
                    XmlNode xmlNode = xmlDocument.SelectSingleNode("/root/step[@code='causeoptimize']");
                    if (xmlNode != null)
                    {
                        Dictionary<string, string> dicElement = new Dictionary<string, string>();
                        string url = xmlNode.Attributes["executefile"].Value;
                        url = url.Replace("{casetype}", dataContext.DataLayerAns.CaseType).Replace("{causecode}", _dataContext.DataLayerAns.CaseCausesList[0].CC_ID);
                        dicElement.Add("fileFullName", url);
                        string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                        dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                        if (elementcofig.result.code.ToString() == "1")
                        {
                            string elementcofigstr = elementcofig.body;
                            OptimizeSourceSerializable optimizeSource = new OptimizeSourceSerializable();
                            _dataContext.DataLayerSys.optimizeFactConfig = optimizeSource.OptimizeCommonSourceContxt(elementcofigstr);
                        }
                    }
                    CaseCauseElementExtraction caseCauseElementExtraction = new CaseCauseElementExtraction();
                    caseCauseElementExtraction._dataContext = _dataContext;
                    caseCauseElementExtraction.moudleName = MoudleName;
                    if (configModel.ConfigDetail != null && configModel.ConfigDetail.FirstOrDefault(a => a.Code == "suitinfouncontested") != null)
                    {
                        XmlDocument xmlDocument1 = new XmlDocument();
                        xmlDocument1.LoadXml(configModel.ConfigDetail.FirstOrDefault(a => a.Code == "suitinfouncontested").ConfigContent);
                        CuaseSuitinfoModel cuaseSuitinfoModel = XmlUtility.DeserializeToObject<CuaseSuitinfoModel>(xmlDocument1.OuterXml);
                        dataContext.InteractiveShow.LogShow($"执行模块编号:{"suitinfouncontested"} 执行code:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "suitinfouncontested").ExecuteCode} 文件路径:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "suitinfouncontested").FilePath}", LogMessageType.Info);
                        if (cuaseSuitinfoModel.casetypeModelList.FirstOrDefault(a=> a.value.ToLower() == dataContext.DataLayerAns.CaseType.ToLower()) !=null)
                        {
                            var casetypemodel = cuaseSuitinfoModel.casetypeModelList.FirstOrDefault(a => a.value.ToLower() == dataContext.DataLayerAns.CaseType.ToLower());
                            if (casetypemodel!=null)
                            {
                                var booktypemodel = casetypemodel.booketypeMdoelList.FirstOrDefault(a => a.value.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                                if (booktypemodel!=null)
                                {
                                    if (booktypemodel.appealElementModels.Count > 0)
                                    {
                                        List<string> list = new List<string>();
                                        string appeal = booktypemodel.appealElementModels[0].ParagraphCode;
                                        if (appeal.IndexOf(",") > -1)
                                        {
                                            list = appeal.Split(',').ToList();
                                        }
                                        else
                                        {
                                            list.Add(appeal);
                                        }
                                        caseCauseElementExtraction.suitinfocode = list;
                                    }
                                    if (booktypemodel.undisputedFackeModels.Count > 0)
                                    {
                                        List<string> list = new List<string>();
                                        string appeal = booktypemodel.undisputedFackeModels[0].ParagraphCode;
                                        if (appeal.IndexOf(",") > -1)
                                        {
                                            list = appeal.Split(',').ToList();
                                        }
                                        else
                                        {
                                            list.Add(appeal);
                                        }

                                        caseCauseElementExtraction.suitin = list;
                                    }
                                    if (booktypemodel.resultElementModelList.Count>0)
                                    {
                                        if (!string.IsNullOrEmpty(booktypemodel.resultElementModelList[0].ParagraphCode))
                                        {
                                            List<string> list = new List<string>();
                                            string str = booktypemodel.resultElementModelList[0].ParagraphCode;
                                            if (str.IndexOf(",")>-1)
                                            {
                                                list = str.Split(',').ToList();
                                            }
                                            else
                                            {
                                                list.Add(str);
                                            }
                                            caseCauseElementExtraction.resultParagraphList = list;
                                        }

                                        if (!string.IsNullOrEmpty(booktypemodel.resultElementModelList[0].PersonStatus))
                                        {
                                            List<string> list = new List<string>();
                                            string str = booktypemodel.resultElementModelList[0].PersonStatus;
                                            if (str.IndexOf(",") > -1)
                                            {
                                                list = str.Split(',').ToList();
                                            }
                                            else
                                            {
                                                list.Add(str);
                                            }
                                            caseCauseElementExtraction.resultPersonnelList = list;
                                        }
                                    }
                                }
                                
                            }
                        }
                    }
                    Stopwatch swtext = new Stopwatch();
                    swtext.Start();
                    caseCauseElementExtraction.ExtElementXmlParse(null, null);
                    swtext.Stop();
                    dataContext.InteractiveShow.LogShow("要素分析调用时长" + swtext.Elapsed.TotalMilliseconds.ToString("0"));
                }

                if (configModel.ConfigDetail != null && configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqxextract") != null)
                {
                    dataContext.InteractiveShow.LogShow($"执行模块编号:{"causeqxextract"} 执行code:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqxextract").ExecuteCode} 文件路径:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqxextract").FilePath}", LogMessageType.Info);
                    Stopwatch swtext = new Stopwatch();
                    swtext.Start();
                    XmlDocument xmlDocument1 = new XmlDocument();
                    xmlDocument1.LoadXml(configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqxextract").ConfigContent);
                    CauseCircumsatanModel causeCircumsatanModel = XmlUtility.DeserializeToObject<CauseCircumsatanModel>(xmlDocument1.OuterXml);
                    List<ParagraphModel> pathModelList = causeCircumsatanModel.casetypeModelList.FirstOrDefault(a => a.Code == dataContext.DataLayerAns.CaseType).CirCasecauseList.FirstOrDefault(a => a.Code == dataContext.DataLayerAns.CaseCausesList[0].CC_ID).docTypeList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).paragraphModelList;
                    foreach (var dataModelResults in dataContext.DataLayerAns.ElementAnalsisDataModelResults)
                    {
                        //情形推导
                        ExtSituationData extSituationData = new ExtSituationData(dataContext, MoudleName) { paragraphModelList = pathModelList,casecauseid=dataModelResults.Key};
                        extSituationData.MatchSituationSupplement(dataModelResults.Value, "","1");
                    }
                    swtext.Stop();
                }

                if (configModel.ConfigDetail != null && configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqjextract") != null)
                {
                    dataContext.InteractiveShow.LogShow($"执行模块编号:{"causeqjextract"} 执行code:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqjextract").ExecuteCode} 文件路径:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqjextract").FilePath}", LogMessageType.Info);
                    Stopwatch swtext = new Stopwatch();
                    swtext.Start();

                    XmlDocument xmlDocument1 = new XmlDocument();
                    xmlDocument1.LoadXml(configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqjextract").ConfigContent);
                    CauseCircumsatanModel causeCircumsatanModel = XmlUtility.DeserializeToObject<CauseCircumsatanModel>(xmlDocument1.OuterXml);
                    List<ParagraphModel> pathModelList = causeCircumsatanModel.casetypeModelList.FirstOrDefault(a => a.Code == dataContext.DataLayerAns.CaseType).CirCasecauseList.FirstOrDefault(a => a.Code == dataContext.DataLayerAns.CaseCausesList[0].CC_ID).docTypeList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).paragraphModelList;

                    foreach (var dataModelResults in dataContext.DataLayerAns.ElementAnalsisDataModelResults)
                    {
                        //情节推导
                        ExtPlotData extPlotData = new ExtPlotData(dataContext, MoudleName) { paragraphModelList = pathModelList,casecauseid=dataModelResults.Key };
                        extPlotData.MatchPlotSupplementCasuse(dataModelResults.Value, "");
                        XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                        XmlDocument xmlDocumentTp = xmlUtilCommon.DataModelByXml(dataModelResults.Value, "");
                        if (dataContext.DataLayerAns.ElementAnalysisResults.ContainsKey(dataModelResults.Key))
                        {
                            dataContext.DataLayerAns.ElementAnalysisResults[dataModelResults.Key] = xmlDocumentTp;
                        }

                        else
                        {
                            dataContext.DataLayerAns.ElementAnalysisResults.Add(dataModelResults.Key, xmlDocumentTp);
                        }

                    }
                    swtext.Stop();
                }

                if (configModel.ConfigDetail != null)
                {
                    if (configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqjextract") != null && configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqxextract") != null)
                    {
                        dataContext.InteractiveShow.LogShow($"执行模块编号:{"causeqjextract"} 执行code:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqjextract").ExecuteCode} 文件路径:{configModel.ConfigDetail.FirstOrDefault(a => a.Code == "causeqjextract").FilePath}", LogMessageType.Info);
                        Stopwatch swtext = new Stopwatch();
                        swtext.Start();

                        //合并情形情节
                        SituationPlotData situationPlotData = new SituationPlotData() { dataContext = dataContext };
                        situationPlotData.Merge();

                        swtext.Stop();
                    }
                }



            }
            if (dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList != null)
                dataContext.DataLayerAns.AnalysisResultsXml = XmlUtility.DataModelByXml(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList);
            #endregion
        }

        
    }
}
